yii2 captcha example

Addcaptcha

Sure! Below is an example of how to implement a CAPTCHA in a Yii2 application using the `yii2-captcha` extension.


Step 1: Install the Extension

--------------------------

The first step is to install the `yii2-captcha` extension. You can do this via Composer by running the following command in your terminal or command prompt:


```bash

composer require yii2mod/yii2-captcha "^2.1"

```


Step 2: Configuration

--------------------

Next, you need to configure the `captcha` component in your Yii2 application's configuration file (usually found in `config/web.php` or `config/main.php`).


```php

return [

// Other configurations...

'components' => [

// Other components...

'captcha' => [

'class' => 'yii\captcha\CaptchaAction',

'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, // Optional, used for testing purposes

// You can customize additional options here if needed, such as font size, length, etc.

],

],

];

```


Step 3: Adding CAPTCHA to a Form

-------------------------------

Now, let's say you have a form that you want to protect with a CAPTCHA. For example, a user registration form.


1. In your form view file (e.g., `views/site/register.php`), add the following code:


```php

use yii\widgets\ActiveForm;

use yii\helpers\Html;


// Form start

$form = ActiveForm::begin(['id' => 'registration-form']);


// Other form fields...


// CAPTCHA field

echo $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::class);


// Submit button

echo Html::submitButton('Register', ['class' => 'btn btn-primary']);


// Form end

ActiveForm::end();

```


2. In the corresponding controller action (e.g., `SiteController`), validate the CAPTCHA:


```php

use yii\web\Controller;

use app\models\RegistrationForm; // Replace this with the actual model for your registration form


class SiteController extends Controller

{

// Other actions...


public function actionRegister()

{

$model = new RegistrationForm();


if ($model->load(Yii::$app->request->post()) && $model->validate()) {

// CAPTCHA validation successful, process the form data

// For example, save the user registration details to the database

// Yii::$app->db->createCommand(...)->execute();


// Redirect or show a success message

return $this->redirect(['site/thank-you']);

}


return $this->render('register', [

'model' => $model,

]);

}


// Other actions...

}

```


That's it! With the above steps, you have successfully added a CAPTCHA to your Yii2 application to protect your user registration form from bots and spam.


Remember to adjust the code according to your actual form model, view, and controller names. Additionally, you can further customize the appearance and behavior of the CAPTCHA widget by exploring the options available in the `yii\captcha\Captcha` class.